﻿package src.flip{
	import flash.display.*;
	import flash.events.*;
	import flash.filters.*;
	import flash.geom.*;
	import flash.media.*;
	import flash.net.*;
	import flash.system.*;
	import flash.text.*;
	import flash.ui.*;
	import flash.utils.*;
	import src.events.*;
	import src.utils.*;
	public final class Flip extends Sprite {
		public static  var COMMA:RegExp = /\s*\,\s*/;
		public static  var flip:Flip;
		public static  var pages:Pages;
		public static  var bar:Bar;
		public static  var zoomer:Zoomer;
		public static  var nav:Nav;
		public static  var printer:Printer;
		public static  var helper:Helper;
		//系统全局配置
		public static  var config:Object = {
			swf_url : "",
			path : "",
			remote : false,
			width : 1000,
			height : 600,
			
			url : "config.xml",
			page_width : 350,
			page_height : 480,
			page_margin : 15,
			zoom : 2,
			speed : 0.2,
			pages : "",
			
			version : "1.0"
		};

		public function Flip():void {
			System.useCodePage = true;
			tabEnabled = false;
			tabChildren = false;
			flip = this;
			//修正IE下Stage宽高为0的bug
			if (stage.stageWidth && stage.stageHeight) {
				init();
			} else {
				stage.addEventListener(Event.RESIZE, iewh);
			}
		}
		private function iewh(e:Event):void {
			if (stage.stageWidth && stage.stageHeight) {
				stage.removeEventListener(Event.RESIZE, iewh);
				init();
			}
		}
		//初始化
		private function init():void {
			//取得用户路径
			var loaderUrl:String = flip.root.loaderInfo.loaderURL;
			config['swf_url'] = loaderUrl;
			var systemUrl:String = loaderUrl.split("?")[0];
			if (systemUrl.lastIndexOf("\\") != -1) {
				config['path'] = systemUrl.slice(0,systemUrl.lastIndexOf("\\") + 1);
			} else {
				config['path'] = systemUrl.slice(0,systemUrl.lastIndexOf("/") + 1);
			}
			//是否在网络
			if (Security.sandboxType == Security.REMOTE) {
				config['remote'] = true;
			} else {
				config['remote'] = false;
			}
			//
			//加载配置
			var config_url:String = flip.root.loaderInfo.parameters.url;
			if (config_url) {
				config['url'] = config_url;
			}
			//Debug.show(config['url']);
			loadConfig();
		}
		private function loadConfig():void {
			var url:String = fU(config['url']);
			var configLoader:URLLoader = new URLLoader();
			configLoader.addEventListener(IOErrorEvent.IO_ERROR, configError, false, 0, true);
			configLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, configError, false, 0, true);
			configLoader.addEventListener(ProgressEvent.PROGRESS, loaderProgress, false, 0, true);
			configLoader.addEventListener(Event.COMPLETE, configHandler, false, 0, true);
			configLoader.load(new URLRequest(url));
		}
		//加载进度事件
		private function loaderProgress(e:ProgressEvent):void {
		}
		//加载配置错误
		private function configError(e:Event):void {
			configNext();
		}
		//加载配置完成
		private function configHandler(e:Event):void {
			//O.o(e.target.data);
			var str:String = e.target.data;
			try {
				var config_xml:XMLList = new XMLList(str);
			} catch (e:Error) {
			}
			//取得全局配置
			var atts:XMLList = config_xml.attributes();
			for each (var att:XML in atts){ 
				var val:String = att.toString();
				if (val) {
					config[att.localName().toLowerCase()] = fS(val);
				}
			}
			configNext();
		}
		//解析配置信息
		private function configNext():void {
			write(flip.root.loaderInfo.parameters);
			mvc();
		}
		private function write(obj:Object):void {
			for (var cfv:String in obj) {
				config[cfv.toLowerCase()] = fS(obj[cfv]);
			}
		}
		private function mvc():void {
			stage.align = "TL";
			stage.scaleMode = "noScale";
			stage.addEventListener(Event.RESIZE, resizeHandler);
			//
			bar = new Bar();
			zoomer = new Zoomer();
			nav = new Nav();
			pages = new Pages();
			//
			addChild(pages);
			addChild(bar);
			addChild(zoomer);
			addChild(nav);
			//
			printer = new Printer();
			helper = new Helper();
			addChild(printer);
			addChild(helper);
			//初始化宽高
			resizeHandler();
		}
		//尺寸改变事件
		private function resizeHandler(e:Event = null):void {
			config['width'] = stage.stageWidth;
			config['height'] = stage.stageHeight;
			sendEvent(FlipEvent.RESIZE);
		}
		
		//格式化相对路径
		public static function fU(url:String):String {
			if(url) {
				var host:String = url.split("?")[0];
				if (host.indexOf(":") != -1) {
					return url;
				} else {
					return config['path'] + url;
				}
			} else {
				return "";
			}
		}
		
		public static function fS(input:*):Object {
			//如果能转数字
			if (!isNaN(Number(input))) {
				return Number(input);
			} else {
				//转字符串
				input = String(input);
				if (input == "true") {
					return true;
				} else if (input == "false") {
					return false;
				} else {
					return input;
				}
			}
		}
		
		public static function fitNumber(num:Number, min:Number, max:Number):Number {
			if (num < min) {
				num = min;
			} else if (num > max) {
				num = max;
			}
			return num;
		}
		
		public static function drawRect(clip:Sprite, rect:Rectangle):void {
			clip.graphics.clear();
			clip.graphics.beginFill(0xffffff, 1);
			clip.graphics.drawRect(rect.x, rect.y, rect.width, rect.height);
			clip.graphics.endFill();
		}
		public static function clearPages(container:DisplayObjectContainer):void {
			while (container.numChildren) {
				var page:Page = container.getChildAt(0) as Page;
				page.remove();
				container.removeChild(page);
			}
		}
		
		public static function getShadow():Array {
			var color:Number = 0x000000;
			var alpha:Number = 0.5;
			var blurX:Number = 6;
			var blurY:Number = 6;
			var strength:Number = 2;
			var inner:Boolean = false;
			var knockout:Boolean = false;
			var quality:Number = BitmapFilterQuality.HIGH;
			var glow:GlowFilter = new GlowFilter(color,alpha,blurX,blurY,strength,quality,inner,knockout);
			return [glow];
		}
		
		public static function fit(clp:DisplayObject, pw:Number, ph:Number):void {
			clp.scaleX = 1;
			clp.scaleY = 1;
			var tw:Number = clp.width;
			var th:Number = clp.height;
			var twh:Number = tw / th;
			var pwh:Number = pw / ph;
			//Debug.show(tw + "|" + th);
			//
			if (twh > pwh) {
				tw = pw;
				th = tw / twh;
			} else {
				th = ph;
				tw = th * twh;
			}
			var tx:Number = pw - tw;
			var ty:Number = ph - th;
			clp.x = Math.round(tx * 0.5);
			clp.y = Math.round(ty * 0.5);
			clp.width = Math.round(tw);
			clp.height = Math.round(th);
		}

		//发送事件
		public static function sendEvent(_type:String, _data:Object = null):void {
			flip.dispatchEvent(new FlipEvent(_type, _data));
			//Debug.show(_type);
		}
	}
}